﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.Mvc;
using System.Transactions;

namespace Web.Areas.Admin.Controllers
{
    public class RoleController : Controller
    {
        private readonly Manager.BLL.Admin.M_AdminRoleBll bll = new Manager.BLL.Admin.M_AdminRoleBll();

        //
        // GET: /Admin/Role/
        [Filters.AdminAuthFilter(ModuleID = (int)Manager.Tools.AuthPermission.ModuleTypes.ManagerRoleSet, Ope = "view")]
        public ActionResult Index()
        {
            return View(bll.GetModelList(string.Empty));
        }

        [Filters.AdminAuthFilter(ModuleID = (int)Manager.Tools.AuthPermission.ModuleTypes.ManagerRoleSet, Ope = "add")]
        public ActionResult Add()
        {
            return View();
        }

        [HttpPost]
        [Filters.AdminAuthFilter(ModuleID = (int)Manager.Tools.AuthPermission.ModuleTypes.ManagerRoleSet, Ope = "add")]
        public ActionResult Add(Manager.Model.Admin.M_AdminRole role)
        {
            try
            {
                if (ModelState.IsValid)
                {
                    int r = bll.Add(role);
                    if (r > 0)
                        return RedirectToAction("Index", "Role");
                    else
                        ModelState.AddModelError("", Resources.Global.msg_error);
                }
            }
            catch
            {
                ModelState.AddModelError("", Resources.Global.msg_error);
            }
            return View(role);
        }

        [Filters.AdminAuthFilter(ModuleID = (int)Manager.Tools.AuthPermission.ModuleTypes.ManagerRoleSet, Ope = "edit")]
        public ActionResult Edit(int id)
        {
            if (!bll.Exists(id))
                return RedirectToAction("Index");
            Manager.Model.Admin.M_AdminRole role = bll.GetModel(id);
            return View(role);
        }

        [HttpPost]
        [Filters.AdminAuthFilter(ModuleID = (int)Manager.Tools.AuthPermission.ModuleTypes.ManagerRoleSet, Ope = "edit")]
        public ActionResult Edit(int id, Manager.Model.Admin.M_AdminRole role)
        {
            if(id==1)
                return Content("<script>alert('" + Resources.Global.msg_operate_alert + "');location.href='/Admin/Role/Index';</script>");
            role.RoleID = id;
            try
            {
                if (ModelState.IsValid)
                {
                    
                    bool r = bll.Update(role);
                    if (r)
                        return RedirectToAction("Index", "Role");
                    else
                        ModelState.AddModelError("", Resources.Global.msg_error);
                }
            }
            catch
            {
                ModelState.AddModelError("", Resources.Global.msg_error);
            }
            return View(role);
        }

        [Filters.AdminAuthFilter(ModuleID = (int)Manager.Tools.AuthPermission.ModuleTypes.ManagerRoleSet, Ope = "del")]
        public ActionResult Del(int id)
        {
            if(id==1)
                return Content("<script>alert('" + Resources.Global.msg_operate_alert + "');location.href='/Admin/Role/Index';</script>");
            if(!bll.Exists(id))
                return Content("<script>alert('" + Resources.Global.msg_select_exist + "');location.href='/Admin/Role/Index';</script>");
            Manager.BLL.Admin.M_AdminBll adminBll = new Manager.BLL.Admin.M_AdminBll();
            int count = adminBll.GetList("RoleId=" + id) == null ? 0 : adminBll.GetList("RoleId=" + id).Tables[0].Rows.Count;
            if (count > 0)
            {
                return JavaScript("<script>alert('" + Resources.Global.msg_delete_error + "');location.href='/Admin/Role/Index';</script>");
            }
            Manager.BLL.Admin.M_RoleModuleBll bllRM = new Manager.BLL.Admin.M_RoleModuleBll();
            bool res = true;
            using (TransactionScope trans = new TransactionScope())
            {
                try
                {
                    bool r = bllRM.DeleteByRoleID(id);
                    bool rs = bll.Delete(id);
                    trans.Complete();
                }
                catch (Exception)
                {
                    res = false;
                }
                finally
                {
                    trans.Dispose();
                }
            }
            if(!res)
                return JavaScript("<script>alert('" + Resources.Global.msg_error + "');location.href='/Admin/Role/Index';</script>");
            return RedirectToAction("Index","Role");
        }

        [Filters.AdminAuthFilter(ModuleID = (int)Manager.Tools.AuthPermission.ModuleTypes.ManagerRoleSet, Ope = "permission")]
        public ActionResult Role(int id)
        {
            Manager.BLL.Admin.M_ModuleBll moduleBll = new Manager.BLL.Admin.M_ModuleBll();
            IList<Models.ModuleItem> modules = new List<Models.ModuleItem>();
            foreach (var item in moduleBll.GetModelList("IsValid=1 and ParentId=0"))
            {
                Models.ModuleItem module = new Models.ModuleItem();
                module.ModuleID = item.ModuleId;
                module.ModuleName = item.ModuleName;
                module.ModuleCode = item.ModuleCode;
                foreach (var child in moduleBll.GetModelList("IsValid=1 and ParentId=" + module.ModuleID))
                {
                    Models.ModuleItem childModule = new Models.ModuleItem();
                    childModule.ModuleID = child.ModuleId;
                    childModule.ModuleName = child.ModuleName;
                    childModule.ModuleCode = child.ModuleCode;
                    childModule.RoleID = id;
                    module.ChildModules.Add(childModule);
                }
                modules.Add(module);
            }
            ViewBag.RoleID = id;
            return View(modules);
        }

        /// <summary>
        /// 提交更新权限表单
        /// </summary>
        /// <returns></returns>
        [HttpPost]
        [Filters.AdminAuthFilter(ModuleID = (int)Manager.Tools.AuthPermission.ModuleTypes.ManagerRoleSet, Ope = "permission")]
        public ActionResult Role(FormCollection forms)
        {
            bool res = true;
            int roleid = int.Parse(forms["RoleID"]);
            using (TransactionScope trans = new TransactionScope())
            {
                try
                {
                    Manager.BLL.Admin.M_RoleModuleBll bllRM = new Manager.BLL.Admin.M_RoleModuleBll();
                    //清空原有权限
                    try
                    {
                        bool rs = bllRM.DeleteByRoleID(roleid);
                    }
                    catch
                    {
                        return Json(new { success = false, msg = Resources.Global.msg_error });
                    }
                    //重新设置权限
                    for (int i = 1; i < forms.AllKeys.Count(); i++)
                    {
                        string cks = forms[i];
                        Manager.Model.Admin.M_RoleModule modelRM = new Manager.Model.Admin.M_RoleModule();
                        modelRM.RoleID = roleid;
                        modelRM.ModuleID = int.Parse(forms.Keys[i]);
                        modelRM.Permission = cks;
                        int r = bllRM.Add(modelRM);
                        if (r == 0)
                            res = false;
                    }
                    trans.Complete();
                }
                catch
                {
                    res = false;
                }
                finally
                {
                    trans.Dispose();
                }
            }
            if(roleid==1)
                return Content("<script>alert('" + Resources.Global.msg_operate_alert + "');location.href='/Admin/Role/Index';</script>");
            if (res)
                return RedirectToAction("Index", "Role");
            else
                return Content("<script>alert('" + Resources.Global.msg_error + "');location.href='/Admin/Role/Index';</script>");
        }
    }
}
